# -*- coding: utf-8 -*-

import time
from datetime import datetime
from log.logger import logger


def time_to_datetime(time_str):
    '''
    Format: 2017-01-01 12:12:12
    '''
    if time_str == '':
        dt = ''
        return dt

    try:
        dt = datetime.strptime(time_str, "%Y-%m-%d %H:%M:%S")
    except Exception, e:
        dt = None
        logger.error('Transfer the time string [{0}] to datetime object failed with error [{1}]'.format(time_str, e))

    return dt


def datetime_to_time(dt):
    '''
    Format: 2017-01-01 12:12:12
    '''
    if not isinstance(dt, datetime):
        time_str = None
        return time_str

    try:
        time_str = dt.strftime("%Y-%m-%d %H:%M:%S")
    except Exception, e:
        time_str = None
        logger.error('Transfer the datetime object [{0}] to time string failed with error [{1}]'.format(dt, e))

    return time_str


def get_now_time():
    # datetime, 2017-09-01 18:18:18.123456
    now_time = datetime.now()
    # string, 2017-09-01 18:18:18
    now_time_str = now_time.strftime("%Y-%m-%d %H:%M:%S")

    return now_time_str


def get_now_datetime():
    # datetime, 2017-09-01 18:18:18.123456
    now_time = datetime.now()
    # string, 2017-09-01 18:18:18
    now_time_str = now_time.strftime("%Y-%m-%d %H:%M:%S")
    now_datetime = datetime.strptime(now_time_str, "%Y-%m-%d %H:%M:%S")

    return now_datetime


def init_datetime():
    # strptime is not thread safe, should be called before initialize the threads
    time.strptime("2012-04-01T00:00:00Z", '%Y-%m-%dT%H:%M:%SZ')
    datetime.strptime("2012-04-01T00:00:00Z", '%Y-%m-%dT%H:%M:%SZ')

    return